import type { TableColumn } from './types'

/** 计算每列像素宽度 */
export function calculateColumnWidths(cols: TableColumn[], tableWidth: number): number[] {
  const widths = new Array(cols.length).fill(0)
  let remaining = tableWidth
  const flexIndexes: number[] = []
  let totalGrow = 0

  cols.forEach((c, i) => {
    if (c.width != null) {
      widths[i] = c.width
      remaining -= c.width
    } else {
      flexIndexes.push(i)
      totalGrow += c.grow ?? 1
    }
  })

  // 4️⃣ 按权重分配剩余空间（性能一次性运算）
  flexIndexes.forEach(i => {
    const grow = cols[i].grow ?? 1
    const raw = totalGrow ? Math.floor((remaining * grow) / totalGrow) : 0
    const min = cols[i].minWidth ?? raw
    widths[i] = Math.max(min, raw)
  })

  /* 再次调节满足 min/max 并消除误差 */
  let diff = tableWidth - widths.reduce((a, b) => a + b, 0)
  for (let i = 0; diff !== 0 && i < widths.length; i++) {
    const step = diff > 0 ? 1 : -1
    const bound = step > 0 ? cols[i].maxWidth ?? Infinity : cols[i].minWidth ?? 40
    while (diff !== 0 && (step > 0 ? widths[i] < bound : widths[i] > bound)) {
      widths[i] += step
      diff -= step
    }
  }

  /* 全局广播：列宽更新 */
  window.dispatchEvent(new Event('vt-column-width-updated'))
  return widths
}

/** 计算固定列的偏移量 */
export function calcFixedOffsets(widths: number[], cols: TableColumn[]) {
  const leftOffsets: Record<string, number> = {}
  const rightOffsets: Record<string, number> = {}

  let accLeft = 0
  cols.forEach((c, i) => {
    if (c.fixed === 'left') {
      leftOffsets[c.key] = accLeft
      accLeft += widths[i]
    }
  })

  let accRight = 0
  for (let i = cols.length - 1; i >= 0; i--) {
    const c = cols[i]
    if (c.fixed === 'right') {
      rightOffsets[c.key] = accRight
      accRight += widths[i]
    }
  }
  return { leftOffsets, rightOffsets }
}
